package pro.softzhang.algo.lc100;

import java.util.Stack;

public class LC150_EvaluateReversePolishNotation {
    public static void main(String[] args) {
        String[] tokens = {"2","1","+","3","*"};
        int res = new Solution1().evalRPN(tokens);
        System.out.println(res);
    }

    static class Solution {
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();

            for (String token : tokens) {
                if(!("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token))) {
                    stack.push(Integer.parseInt(token));
                    continue;
                }

                Integer operand2 = stack.pop(), operand1 = stack.pop(), result = 0;
                switch (token) {
                    case "+":
                        result = operand1 + operand2;
                        break;
                    case "-":
                        result = operand1 - operand2;
                        break;
                    case "*":
                        result = operand1 * operand2;
                        break;
                    case "/":
                        result = operand1 / operand2;
                        break;
                }
                stack.push(result);
            }
            return stack.pop();
        }
    }

    static class Solution1 {
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();
            for (String token : tokens) {
                Integer operand2, operand1;
                switch (token) {
                    case "+":
                        operand2 = stack.pop();
                        operand1 = stack.pop();
                        stack.push(operand1 + operand2);
                        break;
                    case "-":
                        operand2 = stack.pop();
                        operand1 = stack.pop();
                        stack.push(operand1 - operand2);
                        break;
                    case "*":
                        operand2 = stack.pop();
                        operand1 = stack.pop();
                        stack.push(operand1 * operand2);
                        break;
                    case "/":
                        operand2 = stack.pop();
                        operand1 = stack.pop();
                        stack.push(operand1 / operand2);
                        break;
                    default:
                        stack.push(Integer.parseInt(token));
                }
            }
            return stack.pop();
        }
    }
}
